﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;



using MusicPlayerLib.DataModel;

namespace MusicPlayerLib.Utils
{
    /// <summary>
    /// 该类用来处理与播放列表相关的事物;
    /// </summary>
    public class PlaylistUtils
    {

        /// <summary>
        /// 载入指定文件名的播放列表
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static Playlist LoadSingleList(string path)
        {
            Playlist pl = null;
            try
            {
                FileStream fs = new FileStream(path,FileMode.Open);
                XmlSerializer xs = new XmlSerializer(typeof(Playlist));
                pl =(Playlist) xs.Deserialize(fs);
            }
            catch (Exception e)
            {
            }
            return pl;
        }

        /// <summary>
        /// 保存单个播放列表到播放列表文件夹中；
        /// 保存成功则返回文件地址，否则返回string.Empty
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="pl"></param>
        /// <returns></returns>
        public static string SavePlaylist(string dir, Playlist pl)
        {
            if (pl == null)
                return string.Empty;

            //存储的文件以.pl为扩展名;
            string ret = string.Empty;
            try
            {
                string path = dir+ "\\" + pl.Title+".pl";
                //如果同名文件已经存在则删除旧的文件;
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
                XmlSerializer xs = new XmlSerializer(typeof(Playlist));
                xs.Serialize(fs, pl);
                ret = path;
                fs.Close();
            }
            catch (Exception e)
            { }

            return ret;
        }
    }
}
